package core.services.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import core.dao.UserDao;
import core.model.UserEntity;
import core.services.UserService;

public class UserServiceImpl implements UserService, UserDetailsService{

	private UserDao userDao;
	
	
	public boolean createUser(UserEntity userEntity) {
		userDao.save(userEntity);
		return true;
	}


	public UserDao getUserDao() {
		return userDao;
	}


	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	/**
	 * make a UserDetails object requied by spring security
	 */
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		
		UserEntity user = userDao.loadUserByUserName(userName);
		if (user == null)
		{
			throw new UsernameNotFoundException(String.format("No such user with name '%s'", userName));
		}
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		User userDetails = new User(user.getUserName(), user.getPassword(), authorities);
		return userDetails;
	}

}
